package com.media;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.baselibrary.utils.MediaFileUtils;
import com.baselibrary.utils.ToastUtils;
import com.media.image.ImageModel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import co.senab.photoview.PhotoView;
import co.senab.photoview.PhotoViewAttacher;

public class GalleryActivity extends Activity implements View.OnClickListener, ViewPager.OnPageChangeListener {

    private View containerView;
    private PhotoViewPager viewPager = null;
    private GalleryPageAdapter adapter = null;
    private TextView pageCount = null;
    private View back;
    private List<ImageModel> imgs = null;
    private String placeholderImg = null;
    private int pageIndex = 0;
    private View downloadPic;
    private int current = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //去掉状态了
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.media_activity_gallery);

        initData();

        initView();

    }

    private void initData() {
        this.pageIndex = 0;
        this.imgs = new ArrayList<>();
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            ArrayList list = bundle.getParcelableArrayList("data");
            this.imgs = (List<ImageModel>) list.get(0);
            this.pageIndex = bundle.getInt("activeIndex", 0);
            this.placeholderImg = bundle.getString("placeholderImg");
        }
    }

    private void initView() {

        this.containerView = findViewById(R.id.containerView);
        this.back = findViewById(R.id.picBack);
        this.pageCount = findViewById(R.id.page_count);
        this.downloadPic = findViewById(R.id.downloadPic);
        this.back.setOnClickListener(this);

        if (imgs.size() == 1) {
            this.pageCount.setVisibility(View.GONE);
        }
        if (pageIndex >= imgs.size()) {
            pageIndex = 0;
        }
        this.pageCount.setText((pageIndex + 1) + "/" + imgs.size());

        this.adapter = new GalleryPageAdapter();
        this.adapter.setDatas(imgs);
        this.viewPager = findViewById(R.id.viewpager);
        this.viewPager.setOnPageChangeListener(this);
        this.viewPager.setAdapter(adapter);
        this.viewPager.setCurrentItem(pageIndex);
        this.viewPager.setOffscreenPageLimit(0);

        this.downloadPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        final String fileName = System.currentTimeMillis()+".jpg";
                        String filePath = MediaFileUtils.getAppPath(GalleryActivity.this) + fileName;
                        final boolean b = MediaFileUtils.DownLoadFile(getApplication(), imgs.get(current).getPath(), filePath,null);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (b){
                                    ToastUtils.showShort(GalleryActivity.this, "图片已保存至" + fileName + "文件夹");
                                }else {
                                    ToastUtils.showShort(GalleryActivity.this, "下载失败");
                                }
                            }
                        });
                    }
                }).start();
            }
        });

    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.picBack) {
            containerView.setVisibility(View.GONE);
            onBackPressed();

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK) {
            containerView.setVisibility(View.GONE);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        this.pageCount.setText((position + 1) + "/" + imgs.size());
        this.current = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private class GalleryPageAdapter extends PagerAdapter {

        private List<ImageModel> datas = new ArrayList<ImageModel>();

        public GalleryPageAdapter() {
        }

        public void setDatas(List<ImageModel> datas) {
            this.datas.clear();
            this.datas.addAll(datas);
            notifyDataSetChanged();
        }

        public ImageModel getImgDescr(int position) {
            return this.datas.get(position);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            int LayoutId = R.layout.media_view_page_gallery_item;
            View view = LayoutInflater.from(container.getContext()).inflate(LayoutId, container, false);
            PhotoView photoView = view.findViewById(R.id.img);
            String url = datas.get(position).getPath();
            photoView.setLayoutParams(new RelativeLayout.LayoutParams(-1, -1));
            container.addView(view, -1, -1);
            photoView.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener(){
                @Override
                public void onPhotoTap(View view, float x, float y) {
                    containerView.setVisibility(View.GONE);
                    onBackPressed();
                }
            });
            try {
                if (!TextUtils.isEmpty(placeholderImg)) {
                    Drawable placeholder = Drawable.createFromStream(getApplication().getAssets().open(placeholderImg), null);
                    MediaGlideLoader.LoderGalleryImage(getApplication(), url, photoView, placeholder);
                }else {
                    MediaGlideLoader.LoderGalleryImage(getApplication(), url, photoView);
                }
            } catch (IOException e) {
                e.printStackTrace();
                MediaGlideLoader.LoderGalleryImage(getApplication(), url, photoView);
            }
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            return this.datas.size();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(0, 0);
    }

}
